layui.use(['element', 'layer'], function () {
    var element = layui.element;
    var layer = layui.layer;

    window.homeUrl = null;//菜单第一个链接
    window.CONTEXT_PATH = "http://localhost:8080/a/";



    $.ajax({
        url: 'sys/res/getMenuList',
        // url: '/views/test/threemenu.json',
        success: function (result) {
            if (result.success && result.data && result.data.length > 0) {
                if (result.data[0].subList) {
                  if(result.data[0].subList[0].resUrl){
                      homeUrl = result.data[0].subList[0].resUrl;
                  }
                } else {
                   if(result.data[0].resUrl){
                       homeUrl = result.data[0].resUrl;
                   }
                }
                //渲染页面
                renderHtml({
                    targetId: 'index_menu',
                    template: 'menu',
                    htmlData: result,
                    callBack: function () {
                        element.render();
                        //如果由index.html首次进入页面,顶掉页面url历史记录
                        var title = document.title;
                        var hash = (location.hash == "" || location.hash.length === 1) ? homeUrl : location.hash.substring(1);
                        var url = location.protocol + '//' + location.host + location.pathname + location.search + '#' + hash;
                        history.replaceState(null, title, url);
                        // replaceState事件无法手动触发
                        hashchange();
                    }
                })
            }
        }
    });

    //hash监听，用于回退及点击菜单
    window.addEventListener('hashchange', hashchange, false);

    //点击修改密码
    $('#changePassword').click(function () {
        var passIndex = layer.open({
            type: 1,
            title: '密码修改',
            content: $("#edit_pwd"),
            area: ['400px', '300px'],
            shade: 0.6, //遮罩透明度
            anim: 1, //0-6的动画形式，-1不开启
            btn: ['确认修改', '取消'],
            yes: function () {
                var nowpassword = $('#nowpassword').val();
                var password = $('#password').val();
                var repassword = $('#repassword').val();
                if (nowpassword == '') {
                    layer.msg('请输入初始密码');
                } else if (password == '') {
                    layer.msg('请输入新密码');
                } else if (repassword == '') {
                    layer.msg('请确认新密码');
                } else if (password != repassword) {
                    layer.msg('两次密码不一致');
                } else {
                    $.ajax({
                        url: './user/updatepwd',
                        data: {
                            userPwd: nowpassword,
                            userNewPwd: repassword
                        },
                        success: function (result) {
                            if (result.success ) {
                                layer.msg('修改密码成功3s后自动跳转到登录页');
                                localStorage.clear('password');
                                setTimeout(function () {
                                    window.location.href = '/task/views/login.html';
                                }, 3000)

                            } else {
                                layer.msg(result.msg || "操作异常");
                            }
                        },
                        error: function () {
                            layer.msg("操作异常");
                        }
                    });
                }
            },
            end: function () {
                $('#nowpassword').val('');
                $('#password').val('');
                $('#repassword').val('');
            },
        })
    });

    $(document).on("click","a[data-url]", function (e) {
        var $this=$(e.target);
        var hash = $this.attr("data-url");
        if(hash){
            jump(hash);
        }
        // else{
        //     var $three=$this.siblings(".layui-nav-child-three");
        //     if($three.length>0){
        //         var li=$three.children("li:first");
        //         var a=$three.children("li:first").children("a");
        //         $three.children("li:first").children("a").trigger("click");
        //     }
        // }
    });
    $(".smart-menu").on("click",".menu-three-ctr",function () {
        $(this).parent().toggleClass("smart-menu-open");
    });

    $("#userName").text(localStorage.nickname);


    $("#account_nav").on("click","a[data-account]",function (e) {
        var $this=$(this);
        var id=$this.attr("data-id");
        var account=$this.attr("data-account");
        if($(e.target).hasClass("delete")){
            // 删除
            showConfirm("确认删除此账号？",function () {
                ajax({
                    url: '/account/delete',
                    data:{account:account},
                    success: function (result) {
                        if (result.success) {
                            layer.closeAll();
                            layer.msg("操作成功！");
                            getCountStatus();
                        }else{
                            layer.msg("操作失败！");
                        }
                    }
                });
            })
        }else{

        }
    });

    var _hmt=_hmt||[];(function(){var hm=document.createElement("script");hm.src="https://hm.baidu.com/hm.js?f07686635800b1dc0587d91cd81bf3b0";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm,s)})();
    (function(){var bp=document.createElement("script");var curProtocol=window.location.protocol.split(":")[0];if(curProtocol==="https"){bp.src="https://zz.bdstatic.com/linksubmit/push.js"}else{bp.src="http://push.zhanzhang.baidu.com/push.js"}var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(bp,s)})();
});



// 退出
$("#exit").on("click", function () {
    $.ajax({
        url: 'user/logout',
        dataType: "json",
        success: function (result) {
            if (result.success) {
                window.location.href = "/task/views/login.html";
            } else {
                layer.msg("退出失败");
            }
        }
    })
});

/**
 * hashchange的回调函数，渲染右侧
 *
 * @author zhaoqf
 */
function hashchange() {
    var hash = (location.hash == "" || location.hash.length === 1) ? homeUrl : location.hash.substring(1);
    hash = hash.replace(/\[.*\]/, "");
    var temp = "/views" + hash + ".html";
    // 清理ztree数据 important!
    $.fn.zTree && $.fn.zTree.destroy();
    renderHtml({
        targetId: 'index_right',
        template: temp
    });
    var $a = $(".smart-menu a[data-url='" + hash + "']");
    if ($a.length > 0) {
        $a.length > 1 && ($a=$a.eq(0));
        // $a.parents('li').addClass('layui-nav-itemed').siblings('li').removeClass('layui-nav-itemed');
        if($a.hasClass("three")){
            $a.parent("li").addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
            $a.parents("dd").addClass('layui-this').addClass('smart-menu-open').siblings('.layui-this').removeClass('layui-this');
        }else{
            $a.parent("dd").addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
        }
    } else if (location.hash.length > 1) {
        var $alist = $(".smart-menu a[data-url]");
        var h = location.hash.substring(0, location.hash.lastIndexOf("/")).substring(1);
        !!(h) && $alist.each(function (i, v) {
            var $a = $(this);
            var url = $a.attr("data-url").substring(0, location.hash.lastIndexOf("/"));
            if (url.indexOf(h) == 0) {
                $a.parents('li').addClass('layui-nav-itemed').siblings('li').removeClass('layui-nav-itemed');
                $a.parent("dd").addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
                return false;
            }
        })
    }
    layer.closeAll();
}

/**
 * 改变hash方式跳转
 *
 * @author zhaoqf
 */
function jump(hash) {
    // if (getCookie("username")) {
        if(location.hash=="#"+hash){
            hashchange()
        }else {
            location.hash=hash
        }
    // } else {
    //     window.location.href = '/views/login.html'
    // }
}

/**
 * 获取hash中的参数，hash=/aaa/aaa[a=1&b=2]
 *
 * @author zhaoqf
 */
function getHashParam() {
    var hash=location.hash;
    var param=hash.match(/\[(.*)\]/,"");
    if(!param){
        return {};
    }else{
        var arr=param[1].split("&");
        var o={};
        for(var i=0;i<arr.length;i++){
            var d=arr[i].split("=");
            d.length==2 && (o[d[0]]=d[1]);
        }
        return o;
    }
}